package com.glebusheg
{
	import com.bubbler.farm.data.GameFeature;
	import com.bubbler.farm.data.LocalSave;
	import com.bubbler.farm.social.NetworkEvent;
	import com.bubbler.farm.social.NetworkManager;
	import com.bubbler.farm.social.RunMode;
	
	import com.ek.asset.AssetLoader;
	import com.ek.asset.AssetManager;
	import com.ek.core.CoreManager;
	import com.ek.debug.Console;
	import com.ek.debug.Logger;
	import com.ek.text.StringManager;
	import com.ek.ui.UIProgressBar;
	import com.ek.ui.UIText;
	import com.ek.utils.VisualUtil;

	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.system.Security;
	import flash.ui.ContextMenu;
	import flash.ui.ContextMenuBuiltInItems;
	import flash.ui.ContextMenuItem;
	import flash.utils.getDefinitionByName;



	/**
	 * @author eliasku
	 */
	public class Preloader extends MovieClip 
	{
		private static const MAIN_CLASS:String = "AppMain";
		private static const CONTEXT_MENU_STRING:String = "GBS ©2012";
		
		[Embed(source="../static/app_loading.swf", symbol="mc_app_loading")]
		private static const MC_APP_LOADING:Class;
		
		private var _swfLoaded:Boolean;
		
		private var _assetLoader:AssetLoader;
		private var _assetCompleted:Boolean;
        
		private var _preloader:Sprite;
		private var _progressBar:UIProgressBar;
		
		public function Preloader()
		{
			super();
			
			stop();
			
			if(!stage)
				addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			else
				onAddedToStage(null);
		}
		
		private function onAddedToStage(event:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			
			/*** Читаем flash-vars и инициализируем менеджер ресурсов ***/
			var fv:Object = stage.loaderInfo.parameters;
			
			AssetManager.initialize();

			if(fv.hasOwnProperty("version"))
				AssetManager.antiCacheVersion = fv["version"];

			if(fv.hasOwnProperty("asset_url"))
				AssetManager.assetURL = fv["asset_url"];
			else
				AssetManager.assetURL = "asset";
			
			//setupContextMenu();
		
			_preloader = new MC_APP_LOADING();
			if(_preloader)
			{
				_preloader.x = stage.stageWidth * 0.5;
				_preloader.y = stage.stageHeight * 0.5;
				addChildAt(_preloader, 0);
				
/*				_progressBar = new UIProgressBar(null, _preloader["progress_bar"]);
				_progressBar.progress = 0.0;
				_progressBar.text = "0%";*/
			}
			
			var preloaderURL:String = "swf/preloader.swf";
			if(fv.hasOwnProperty("preloader_swf"))
				preloaderURL = fv["preloader_swf"];
				
			AssetManager.add("mc_preloader", preloaderURL, false, "mc_preloader");
			
			_assetLoader = AssetManager.load();
			_assetLoader.addEventListener(Event.COMPLETE, onPreloaderLoaded);
			_assetLoader.load();
			
			stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}
		
		private function onPreloaderLoaded(event:Event):void
		{
			_assetLoader = null;
			_assetCompleted = true;
		}

/*		private function setupContextMenu():void 
		{
			var cm:ContextMenu = new ContextMenu();
			var bii:ContextMenuBuiltInItems = cm.builtInItems;
			var items:Array = new Array();
			var cmi:ContextMenuItem = new ContextMenuItem(CONTEXT_MENU_STRING, true, true, true);
			
			items.push(cmi);
			cm.customItems = items;
			
			bii.loop = false;
			bii.forwardAndBack = false;
			bii.play = false;
			bii.print = false;
			bii.rewind = false;
			bii.save = false;
			bii.zoom = false;
			
			CoreManager.root.contextMenu = cm;
			this.contextMenu = cm;
		}*/
		
		private function onEnterFrame(event:Event):void 
		{
			var bytesLoaded:uint = root.loaderInfo.bytesLoaded;
			var bytesTotal:uint = root.loaderInfo.bytesTotal;
			var assetProgress:Number = 0.0;
			var baseProgress:Number = 0.0;
			var progress:Number = 0.0;
			
			if(_assetLoader)
				assetProgress = _assetLoader.progress;
			
			if(_assetCompleted)
				assetProgress = 1.0;
				
			if(bytesTotal > 0)
				baseProgress = Number(bytesLoaded / bytesTotal);
				
			progress = 0.5*(assetProgress + baseProgress);
			
			if(!_swfLoaded && bytesLoaded >= bytesTotal)
				_swfLoaded = true;
			
			if(_assetCompleted && _swfLoaded)
			{
				stage.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
				start();
			}
			else
			{
				if(_progressBar)
				{
					_progressBar.progress = progress;
					_progressBar.text = int(progress*100).toString() + "%";
				}
			}
		}

		private function start():void
        {
			nextFrame();
			
			var mainCls:Class = getDefinitionByName(MAIN_CLASS) as Class;
            var main:DisplayObject = new mainCls();
			
			//CoreManager.root.addChild(main);
            
            if(parent) parent.removeChild(this);
		}
	}
}
